<template>
    <div class="canvas-container">
      <div class="canvas-header">
        <div class="canvas-info">
          <span class="canvas-size">1000 × 600 px</span>
          <span class="canvas-status" :class="roomStore.gameStatus">
            {{ getStatusText(roomStore.gameStatus) }}
          </span>
        </div>
        <div class="canvas-controls">
          <div class="brush-preview" :style="{ backgroundColor: currentBrushColor }"></div>
          <div class="color-info">{{ currentBrushColor }}</div>
          <!-- 画笔大小固定为12px，不再显示 -->
        </div>
      </div>
      <div class="canvas-wrapper">
        <canvas 
          ref="canvas" 
          @mousedown="startPaint" 
          @mousemove="handleMouseMove" 
          @mouseup="stopPaint"
          @mouseleave="stopPaint"
          class="game-canvas"
          :class="{ 'painting': isPainting.value, 'disabled': roomStore.gameStatus !== 'playing' }"
        />
        <!-- 网格背景叠加层 -->
        <div class="grid-overlay"></div>
        <!-- 画笔预览 -->
        <div 
          v-if="showBrushPreview && roomStore.gameStatus === 'playing'" 
          class="cursor-preview"
          :style="{
            left: brushPreviewPos.x + 'px',
            top: brushPreviewPos.y + 'px',
            width: gameStore.brushSize + 'px',
            height: gameStore.brushSize + 'px',
            backgroundColor: currentBrushColor,
            opacity: 0.5
          }"
        ></div>
      </div>
      <div class="canvas-footer">
        <div class="paint-instructions" v-if="roomStore.gameStatus === 'playing'">
          <span>按住鼠标左键进行涂色</span>
        </div>
        <div class="canvas-zoom">
          <button 
            class="zoom-btn" 
            @click="zoomOut"
            :disabled="currentZoom <= 0.5"
          >
            －
          </button>
          <span class="zoom-level">{{ Math.round(currentZoom * 100) }}%</span>
          <button 
            class="zoom-btn" 
            @click="zoomIn"
            :disabled="currentZoom >= 2"
          >
            ＋
          </button>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted, computed, watch } from 'vue'
  import { useGameStore } from '@/stores/game'
  import { useRoomStore } from '@/stores/room'
  import { getCanvasPoint } from '@/utils/canvas'
  import { socketService } from '@/services/socketService'
  
  const canvas = ref(null)
  const canvasContainer = ref(null)
  const isPainting = ref(false)
  const showBrushPreview = ref(false)
  const brushPreviewPos = ref({ x: 0, y: 0 })
  const currentZoom = ref(1)
  
  const gameStore = useGameStore()
  const roomStore = useRoomStore()
  
  // 監聽當前玩家顏色變化
  watch(() => {
    const currentPlayer = roomStore.players.find(p => p.isCurrent)
    return currentPlayer?.color
  }, (newColor, oldColor) => {
    if (newColor && newColor !== '#000' && newColor !== oldColor) {
      console.log(`檢測到玩家顏色變化: ${oldColor} -> ${newColor}`)
      gameStore.myColor = newColor
    }
  }, { immediate: true })
  
  // 計算當前畫筆顏色
  const currentBrushColor = computed(() => {
    const currentPlayer = roomStore.players.find(p => p.isCurrent)
    const playerColor = currentPlayer?.color
    const gameColor = gameStore.myColor
    
    // 優先使用玩家顏色，如果沒有則使用遊戲狀態中的顏色
    if (playerColor && playerColor !== '#000') {
      return playerColor
    } else if (gameColor && gameColor !== '#000') {
      return gameColor
    } else {
      return '#000000'
    }
  })
  
  onMounted(() => {
    gameStore.initCanvas(canvas.value)
    resizeCanvas()
    
    // 延迟同步当前玩家颜色，确保玩家数据已加载
    setTimeout(() => {
      const currentPlayer = roomStore.players.find(p => p.isCurrent)
      if (currentPlayer && currentPlayer.color && currentPlayer.color !== '#000') {
        console.log(`画布初始化时同步玩家颜色: ${currentPlayer.color}`)
        gameStore.myColor = currentPlayer.color
      } else {
        console.log('画布初始化时未找到有效的玩家颜色')
      }
    }, 500)
    
    // 监听窗口大小变化
    window.addEventListener('resize', resizeCanvas)
    // 监听鼠标移动以显示画笔预览
    document.addEventListener('mousemove', updateBrushPreview)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', resizeCanvas)
    document.removeEventListener('mousemove', updateBrushPreview)
  })

  // 调整画布大小以匹配容器
  const resizeCanvas = () => {
    if (!canvas.value) return
    
    const wrapper = canvas.value.parentElement
    // 获取容器可用大小（减去内边距和边框）
    const rect = wrapper.getBoundingClientRect()
    
    console.log('调整画布大小:', rect.width, 'x', rect.height)
    
    // 设置canvas元素的宽高属性（这会影响绘图坐标系）
    canvas.value.width = rect.width
    canvas.value.height = rect.height
    
    // 重新设置画布背景为白色
    const ctx = canvas.value.getContext('2d')
    ctx.fillStyle = '#FFFFFF'
    ctx.fillRect(0, 0, canvas.value.width, canvas.value.height)
    
    console.log('画布大小调整完成:', canvas.value.width, 'x', canvas.value.height)
    
    // 重置缩放
    currentZoom.value = 1
    canvas.value.style.transform = 'none'
  }
  
  onUnmounted(() => {
    document.removeEventListener('mousemove', updateBrushPreview)
  })
  
  // 获取状态文本
  const getStatusText = (status) => {
    const statusMap = {
      'waiting': '等待游戏开始',
      'playing': '游戏进行中',
      'finished': '游戏已结束'
    }
    return statusMap[status] || status
  }
  
  // 开始绘画
  const startPaint = (e) => {
    // 只允许在playing状态下涂色
    if (roomStore.gameStatus !== 'playing') {
      console.warn(`游戏状态不允许涂色 (当前: ${roomStore.gameStatus})`)
      return
    }
    isPainting.value = true
    paint(e)
  }
  
  // 处理鼠标移动
  const handleMouseMove = (e) => {
    if (!isPainting.value) return
    paint(e)
  }
  
  // 停止绘画
  const stopPaint = () => {
    isPainting.value = false
  }
  
  // 定义网格大小常量（应与后端保持一致）
  const GRID_SIZE = 10
  
  // 绘画函数
  function paint(e) {
    if (!canvas.value) {
      console.warn('画布未初始化，跳过涂色操作')
      return
    }
    
    // 更宽松的游戏状态检查
    if (roomStore.gameStatus !== 'playing') {
      console.warn(`游戏状态不是playing (当前: ${roomStore.gameStatus})，跳过涂色操作`)
      return
    }
    
    const { x, y } = getCanvasPoint(canvas.value, e)
    
    // 确保使用当前玩家的颜色
    const currentPlayer = roomStore.players.find(p => p.isCurrent)
    let playerColor = '#000000' // 默认颜色
    
    if (currentPlayer && currentPlayer.color && currentPlayer.color !== '#000') {
      playerColor = currentPlayer.color
      console.log(`使用当前玩家颜色进行涂色: ${playerColor}`)
    } else {
      console.warn('当前玩家未设置有效颜色，使用默认黑色')
    }
    
    // 使用玩家颜色，但不强制覆盖游戏状态中的颜色
    if (gameStore.myColor !== playerColor) {
      gameStore.myColor = playerColor
      console.log(`更新游戏颜色以匹配玩家颜色: ${gameStore.myColor}`)
    }
    
    // 调整绘制位置，考虑画笔大小，确保绘制在鼠标位置中心
    const adjustedX = x - gameStore.brushSize / 2
    const adjustedY = y - gameStore.brushSize / 2
    
    // 确保画布上下文使用正确的颜色
    if (gameStore.ctx) {
      gameStore.ctx.fillStyle = playerColor
    }
    
    // 在本地画布上绘制
    console.log(`准备绘制: 位置(${adjustedX},${adjustedY}), 颜色: ${playerColor}`)
    gameStore.drawPixel(adjustedX, adjustedY)
    
    // 获取房间ID和当前玩家ID
    const roomId = roomStore.roomId
    const playerId = currentPlayer ? currentPlayer.id : null
    
    console.log(`准备发送涂色操作: 房间ID=${roomId}, 玩家ID=${playerId}`)
    
    // 如果有房间ID和玩家ID，则发送到后端
    if (roomId && playerId) {
      // 计算画布大小
      const canvasWidth = canvas.value.width
      const canvasHeight = canvas.value.height
      
      // 将像素坐标转换为网格坐标（0-9范围）
      const gridX = Math.floor((x / canvasWidth) * GRID_SIZE)
      const gridY = Math.floor((y / canvasHeight) * GRID_SIZE)
      
      // 确保网格坐标在有效范围内
      const clampedGridX = Math.max(0, Math.min(GRID_SIZE - 1, gridX))
      const clampedGridY = Math.max(0, Math.min(GRID_SIZE - 1, gridY))
      
      console.log('发送涂色操作 - 像素坐标:', {x, y}, '转换为网格坐标:', {gridX: clampedGridX, gridY: clampedGridY})
      socketService.emitPaint(roomId, playerId, clampedGridX, clampedGridY)
    } else {    
      console.warn('缺少房间ID或玩家ID，无法发送涂色操作')
    }
    
    // 无论是否连接后端，都更新本地面积统计
    gameStore.updateAreas()
    
    // 记录涂色操作完成
    console.log('本地涂色操作完成')
  }
  
  
  // 更新画笔预览位置
  const updateBrushPreview = (e) => {
    if (!canvas.value || roomStore.gameStatus !== 'playing') return
    
    const rect = canvas.value.getBoundingClientRect()
    const isOverCanvas = (
      e.clientX >= rect.left && e.clientX <= rect.right &&
      e.clientY >= rect.top && e.clientY <= rect.bottom
    )
    
    showBrushPreview.value = isOverCanvas
    
    if (isOverCanvas) {
      // 计算相对于画布容器的位置
      brushPreviewPos.value = {
        x: e.clientX - rect.left - gameStore.brushSize / 2,
        y: e.clientY - rect.top - gameStore.brushSize / 2
      }
    }
  }
  
  // 放大画布
  const zoomIn = () => {
    if (currentZoom.value < 2) {
      currentZoom.value += 0.1
      updateCanvasZoom()
    }
  }
  
  // 缩小画布
  const zoomOut = () => {
    if (currentZoom.value > 0.5) {
      currentZoom.value -= 0.1
      updateCanvasZoom()
    }
  }
  
  // 更新画布缩放
  const updateCanvasZoom = () => {
    if (canvas.value) {
      canvas.value.style.transform = `scale(${currentZoom.value})`
      canvas.value.style.transformOrigin = 'center center'
    }
  }
  </script>
  
 <style scoped>
.canvas-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 12px;
  background: var(--surface-glass);
  border-radius: 12px;
  border: 1px solid rgba(255, 255, 255, 0.1);
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  margin: 0;
  box-sizing: border-box;
}

/* 确保canvas-wrapper能够正确约束画布 */
.canvas-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  overflow: auto;
  background: var(--surface-glass);
  border-radius: 8px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

/* 让画布能够完全填充容器大小 */
  .game-canvas {
    width: 100%;
    height: 100%;
    border: 2px solid var(--border);
    border-radius: 8px;
    cursor: crosshair;
    background: white;
    transition: all 0.3s ease;
    image-rendering: pixelated;
  }

  /* 确保canvas-wrapper能够正确约束画布 */
  .canvas-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    overflow: hidden;
    background: var(--surface-glass);
    border-radius: 8px;
    border: 1px solid rgba(255, 255, 255, 0.1);
    min-height: 0;
  }

.canvas-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.canvas-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.canvas-size {
  font-size: 12px;
  color: var(--text-muted);
}

.canvas-status {
  font-size: 12px;
  padding: 4px 12px;
  border-radius: 16px;
  font-weight: 500;
}

.canvas-status.waiting {
  background: rgba(255, 230, 109, 0.2);
  color: var(--warning);
}

.canvas-status.playing {
  background: rgba(78, 205, 196, 0.2);
  color: var(--success);
}

.canvas-status.finished {
  background: rgba(255, 107, 107, 0.2);
  color: var(--error);
}

.canvas-controls {
      display: flex;
      align-items: center;
      gap: 8px;
    }

.brush-preview {
      width: 28px;
      height: 28px;
      border-radius: 50%;
      border: 2px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 2px 6px rgba(0, 0, 0, 0.25);
      transition: all 0.3s ease;
    }
    
.color-info {
      font-size: 12px;
      color: var(--text-muted);
      font-family: monospace;
    }
    
    .brush-preview:hover {
      transform: scale(1.1);
      box-shadow: 0 3px 8px rgba(0, 0, 0, 0.35);
    }

/* 画布特有状态样式 */

.game-canvas.painting {
  cursor: grabbing;
  border-color: var(--primary);
  box-shadow: 0 0 15px rgba(78, 205, 196, 0.5);
}

.game-canvas.disabled {
  cursor: not-allowed;
  opacity: 0.6;
}

.grid-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    linear-gradient(rgba(0, 0, 0, 0.05) 1px, transparent 1px),
    linear-gradient(90deg, rgba(0, 0, 0, 0.05) 1px, transparent 1px);
  background-size: 20px 20px;
  pointer-events: none;
  z-index: 10;
}

.cursor-preview {
  position: absolute;
  border-radius: 50%;
  pointer-events: none;
  z-index: 20;
  transform: translate(-50%, -50%);
  transition: width 0.1s, height 0.1s, background-color 0.1s;
}

.canvas-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 4px;
}

.paint-instructions {
  font-size: 12px;
  color: var(--text-muted);
}

.canvas-zoom {
  display: flex;
  align-items: center;
  gap: 8px;
}

.zoom-btn {
  width: 24px;
  height: 24px;
  border-radius: 4px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  background: rgba(255, 255, 255, 0.05);
  color: var(--text-primary);
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
}

.zoom-btn:hover:not(:disabled) {
  background: rgba(255, 255, 255, 0.1);
  border-color: rgba(255, 255, 255, 0.3);
}

.zoom-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.zoom-level {
  font-size: 12px;
  color: var(--text-muted);
  min-width: 40px;
  text-align: center;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .canvas-container {
    padding: 12px;
    gap: 8px;
  }
  
  .canvas-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .canvas-controls {
    align-self: flex-end;
  }
  
  .canvas-footer {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .canvas-zoom {
    align-self: flex-end;
  }
}

@media (max-width: 480px) {
  .game-canvas {
    max-width: 100%;
    height: auto;
  }
}
</style>